﻿package ua.mihaylenko.cardsplugin.common{
	import fl.data.DataProvider;
	import flash.display.Sprite;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.text.TextField;
	import flash.events.MouseEvent;
	import fl.transitions.Tween;
	import fl.transitions.TweenEvent;
	import fl.transitions.easing.Strong
	import ua.mihaylenko.cardsplugin.components.EmbedPanel;
	import ua.mihaylenko.cardsplugin.components.thumbs.*;
	import ua.mihaylenko.cardsplugin.data.*;
	import ua.mihaylenko.cardsplugin.components.cardeditor.ECEdit;
	import ua.mihaylenko.cardsplugin.cardsviwer.Card;
	import ua.mihaylenko.cardsplugin.tabBar.TabBar;
	import ua.mihaylenko.cardsplugin.tabBar.TabEvent;
	import ua.mihaylenko.cardsplugin.utils.ToolTip;
	import flash.utils.setTimeout;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.net.*;
	import flash.xml.*;
	
	public dynamic class EngineMain extends Sprite
	{
		private static const ZPURL:String = "http://www.zetaprints.com/";
		public static var instance:EngineMain;
		public var _smcThumbNovigate:ThumbNovigate;
		public var _cursor:Sprite;
		public var _smcLogo:Sprite;
		public var _smcCard:Card;
		public var _smcLoading:MovieClip;		
		public var _smcCardEditor:ECEdit;
		public var _tabBar:TabBar;
		public var _embedPanel:EmbedPanel;
		public var _bg:Sprite;
		private var _cXMLParcer:XMLParcer;
		private var _twLoading:Tween;
		private var _bEdit:Boolean;
		private var _smcLogoToolTip:ToolTip;
		private var tabData:Array = [ "Designs", "Embed" ];
		
		private var _tobeOpenSmcCard:Card = null;
		
		public function EngineMain()
		{
			InitFlashVars();

			var loader:URLLoader = new URLLoader();
			var url:String = FlashVars.getInstance().getData('params');
			//url = 'http://order.uprintinvitations.com/?page=template-xml;TemplateID=38B2C346-AE94-4366-A713-6714A25CB634';
			var request:URLRequest = new URLRequest(url);
			
			init();
			
			loader.addEventListener(Event.COMPLETE, function(event:Event):void{
			    var xXML:XMLDocument = new XMLDocument(loader.data);trace(loader.data);trace(xXML.firstChild.nodeName);
				var single:String = (xXML.firstChild.nodeName == 'rss') ? 'false' : 'true';
				FlashVars.getInstance().setData('singletemplate', single);
				
				tabData = generateTabData();
				_tabBar.dataProvider = new DataProvider(tabData);
				
				// check the mode and call templates URL or single template url
				if(FlashVars.getInstance().isSingleTemplate()){
					retrieveSingleTemplate();
				}else{
					_cXMLParcer = new XMLParcer( { _function:configurationLoaded, _object:instance } );
				}
			});
			
            try {
                loader.load(request);
            } catch (error:Error) {
                trace("Unable to load requested document: "+url);
            }

			
		}
		
		private function init():void{
			_smcCard.onInitialaze( _smcLogo );
			_smcLogo.buttonMode = true;
			_smcLogo.addEventListener(MouseEvent.CLICK, smcLogoClickEventHandler);
			
			_smcLogoToolTip = new ToolTip("Click to go to zetaprints.");		
			_smcLogoToolTip.attach(_smcLogo);
			_bg.scale9Grid = new Rectangle(1, 1, 550, 338);
			_smcLoading._bg.scale9Grid = new Rectangle(1, 1, 550, 338);
			
			this.tabData = this.generateTabData();
			_tabBar.dataProvider = new DataProvider(tabData);
			_tabBar.visible = false;
			_tabBar.selectedIndex = 0;
			_tabBar.addEventListener(TabEvent.TABCHANGE, tabChangeHandler);
			_embedPanel.visible = false;
			_cursor.mouseEnabled = false;
			_cursor.visible = false;
			DocumentClass.AppStage.addEventListener(Event.RESIZE, stageResizeEventHandler);
			resize();
			
			instance = this;
		}
		
		private function configurationLoaded(bLoaded:Boolean)
		{
			if(bLoaded){
				_smcThumbNovigate.onInitialaze(DataManager.getInstance().thumbs);
				_smcThumbNovigate.addListener(MouseEvent.MOUSE_OVER, {_function:onThumbOver, _object:this});
				_smcThumbNovigate.addListener(MouseEvent.MOUSE_OUT, {_function:onThumbOut, _object:this});
				_smcThumbNovigate.addListener(MouseEvent.CLICK, {_function:onThumbClick, _object:this});
				_smcCardEditor.oHide = {Function:closeEditCard, Object:this};
				_smcCardEditor.fLoading = showLoading;
				_smcCardEditor.fLoaded = hideLoading;
				_tabBar.visible = true;				
				hideLoading();
			}else{
				trace("Eroors handler(Configuration not loaded)");
			}
		}
		private function closeEditCard(){
			_bEdit = false;
			_smcCardEditor.hide();
			_smcThumbNovigate.show();
			_smcCard.removeImage();
			_smcCard.hide();	
			_smcCard.visible = true;
			_tabBar.dataProvider = new DataProvider(tabData);
			_tabBar.selectedIndex = 0;
		}
		private function hideLoading(){
			if(_twLoading){
				_twLoading.stop();
			}
			
//			_twLoading = new Tween(_smcLoading, "y", Elastic.easeOut, 0, -_smcLoading.height, 20, false);
			_twLoading = new Tween(_smcLoading, "alpha", Strong.easeInOut, 1, 0, 30, false);
			//new Tween(_smcLoadingBar, "alpha", Strong.easeInOut, 1, 0, 30, false);
			_twLoading.addEventListener(TweenEvent.MOTION_FINISH, closeLoading);
		}
		private function closeLoading(oEvent:TweenEvent){
			_smcLoading._smcLoadingBar._smcAnimation.gotoAndStop(1);
			_smcLoading.visible = false;			
		}
		private function showLoading(){
			if(_twLoading){
				_twLoading.stop();
				if(_twLoading.hasEventListener(TweenEvent.MOTION_FINISH) ){
				   _twLoading.removeEventListener(TweenEvent.MOTION_FINISH, closeLoading);
				}
			}
			_smcLoading._smcLoadingBar.x = (DocumentClass.AppStage.stageWidth - _smcCardEditor._smcBG.width) / 2 - 74;
			_smcLoading._smcLoadingBar.y = (DocumentClass.AppStage.stageHeight - 170) / 2;
			_smcLoading._smcLoadingBar._smcAnimation.gotoAndPlay(2);
			_smcLoading.visible = true;
			_twLoading = new Tween(_smcLoading, "alpha", Strong.easeInOut, 0, 1, 30, false);
//			_twLoading = new Tween(_smcLoading, "y", Elastic.easeOut, -_smcLoading.height, 0, 20, false);
		}
		private function onThumbOver(oEvent:DataThumb){
			if(!_bEdit){
				_smcCard.show(oEvent);
			}
		}
		private function onThumbOut(oEvent:DataThumb){
			if(!_bEdit){
				_smcCard.hide();
			}
		}
		private function onThumbClick(oEvent:DataThumb) {
			if(_smcCard.loaded){
				this.enterTemplateEdit();
				
				//if designer details present and its first time, activete embed tab
				if(oEvent.designerInfoFirstTime==true){
					setTimeout(function():void { _tabBar.selectedIndex = 1; }, 50);
					oEvent.designerInfoFirstTime=false;
				}				
			}else{
			    this._tobeOpenSmcCard = _smcCard;
				_smcCard.setLoadedListener({_function: cardLoadedHandler, _object: this});
			}
		}
		
		// open template's edit mode
		private function enterTemplateEdit():void{
			_bEdit = true;
			
			_smcCardEditor.show({url:_smcCard.imageUrl, 
								 accessUrl: _smcCard._sSuccesURL, 
								 image:_smcCard.bitmap, 
								 id:_smcCard.id, 
								 filds:_smcCard.filds, 
								 images:_smcCard.images,
								 download: _smcCard._sDownload,
								 multipage: _smcCard._multipage});
			
			_smcThumbNovigate.hide();
			_smcCard.visible = false;
			_tabBar.selectedIndex = -1;
			//tabData.push("Stock images");
			//_tabBar.dataProvider = new DataProvider(tabData);
			
			//update embed panel with designer details(by sharwan)
			_embedPanel.updateData(_smcCard);
		}
		
		private function cardLoadedHandler(_card:Card):void{
			if(this._tobeOpenSmcCard == _card){
				_smcCard = this._tobeOpenSmcCard;
				this._tobeOpenSmcCard = null;
				
				this.enterTemplateEdit();
				setTimeout(function():void { _tabBar.selectedIndex = 1; }, 50);
			}
		}
		
		private function tabChangeHandler(event:TabEvent):void
		{
			switch (event.label)
			{
				case "Designs":
					//set the null value for designer's details(by sharwan)
					_embedPanel.updateData(null);
					
					_embedPanel.visible = false;
					_smcThumbNovigate.visible = true;
					if (_smcCardEditor.visible)
					{
						closeEditCard();
					}									
					break;
				case "Stock images":					
					_embedPanel.visible = false;
					if (_smcCardEditor.visible)
					{
						_smcCardEditor._smcThumbNovigate.visible = true;
					}
					break;
				case "Embed":
					//_smcCard.visible = false;
					_smcThumbNovigate.visible = false;
					_embedPanel.visible = true;
					if (_smcCardEditor.visible)
					{
						_smcCardEditor._smcThumbNovigate.visible = false;
					}
					break;
			}
		}
		
		private function smcLogoClickEventHandler(event:MouseEvent):void
		{
			var request:URLRequest = new URLRequest(ZPURL);            
            navigateToURL(request, "_blank");
		}
		
		private function InitFlashVars(){
			FlashVars.getInstance().initFlashVars(parent);
		}
		
		private function stageResizeEventHandler(event:Event):void
		{
			resize();			
		}
		private function resize():void
		{
			_smcLoading._bg.width = DocumentClass.AppStage.stageWidth;
			_smcLoading._bg.height = DocumentClass.AppStage.stageHeight;
			_smcLoading._smcLoadingBar.x = (DocumentClass.AppStage.stageWidth - _smcCard._smcRight.width) / 2;
			_smcLoading._smcLoadingBar.y = (DocumentClass.AppStage.stageHeight - 100) / 2;
			_bg.width = DocumentClass.AppStage.stageWidth;
			_bg.height = DocumentClass.AppStage.stageHeight;
			//----Kohl: It is not necessary!------
			//_smcLogo.x = (DocumentClass.AppStage.stageWidth - _smcLogo.width) / 2;
			//_smcLogo.y = (DocumentClass.AppStage.stageHeight - 66 - _smcLogo.height) / 2;
			//------------end---------
			//_smcThumbNovigate.x = (DocumentClass.AppStage.stageWidth - 490) / 2;
			_smcThumbNovigate.y = DocumentClass.AppStage.stageHeight - 60;
			_smcThumbNovigate.resize(DocumentClass.AppStage.stageWidth - 60);
			_smcCard.resize(DocumentClass.AppStage.stageWidth, DocumentClass.AppStage.stageHeight);
			_smcCardEditor.resize(DocumentClass.AppStage.stageWidth, DocumentClass.AppStage.stageHeight);
			_tabBar.y = _smcThumbNovigate.y - 26;
			_embedPanel.y = _smcThumbNovigate.y + 10;
			
			
			_embedPanel.orderPrintBtn.x=DocumentClass.AppStage.stageWidth-(_embedPanel.orderPrintBtn.width+15);
			_embedPanel.designerNameBtn.x=DocumentClass.AppStage.stageWidth-(_embedPanel.designerNameBtn.width+15);
			_embedPanel._embedDesignerTxt.x=_embedPanel.designerNameBtn.x-(_embedPanel._embedDesignerTxt.width);
			_embedPanel._embedCommentTxt.x=_embedPanel.copyBtn.x+_embedPanel.copyBtn.width+15;
			_embedPanel._embedCommentTxt.width=DocumentClass.AppStage.stageWidth-(_embedPanel._embedCommentTxt.x+10);
		}
		
		// generate tabs according to the view mode.
		private function generateTabData():Array{
		    if(FlashVars.getInstance().isSingleTemplate()){
			    return [ "Embed" ];
			}else{
			    return [ "Designs", "Embed" ];
			}
		}
		
		private function initDomainParam(sURL:String):void{
			var aDomain:Array = sURL.split("/");
			aDomain.splice(3, aDomain.length-1);
			
			FlashVars.getInstance().setData("domain", aDomain.join("/"));
		}
		
		// perform single template mode
		private function retrieveSingleTemplate():void{
			var url:String = FlashVars.getInstance().getData('params');
			//url = 'http://order.uprintinvitations.com/?page=template-xml;TemplateID=38B2C346-AE94-4366-A713-6714A25CB634';
			this.initDomainParam(url);
			
		    var cData:DataThumb = new DataThumb();
			var pos:Number = url.lastIndexOf("=");
			cData.id = url.substring(pos+1);
		    
			DataManager.getInstance().thumbs = [cData];
		    this.configurationLoaded(true);
			//hideLoading();
			_smcCard.show(cData);
			
			var timer:Timer = new Timer(50, 0);
			timer.addEventListener(TimerEvent.TIMER, function():void{
				if(_smcCard.loaded){
					enterTemplateEdit();
					
					//if designer details present and its first time, activete embed tab
					if(cData.designerInfoFirstTime==true){
						setTimeout(function():void { _tabBar.selectedIndex = 1; }, 50);
						cData.designerInfoFirstTime=false;
					}
					_tabBar.selectedIndex = 0;
					timer.stop();
				}
			});
			
			timer.start();
		}
	}
}